/**
 * 单词服务模块 - 管理单词数据和学习进度
 */
import * as api from './api.js';
import storage from '@system.storage';

// 存储键
const DAILY_WORDS_KEY = 'daily_words';
const WORD_HISTORY_KEY = 'word_history';
const LAST_SYNC_KEY = 'last_sync_time';

/**
 * 单词模型类
 */
export class WordModel {
    constructor(data) {
        this.id = data.id || 0;
        this.word = data.word || '';
        this.mean = data.mean || '';
        this.phonetic_symbol = data.phonetic_symbol || '';
        this.initial = data.initial || '';
        this.difficulty = data.difficulty || 1;
        this.frequency = data.frequency || 0;
        this.topic = data.topic || '';
        this.part_of_speech = data.part_of_speech || '';
        this.isMastered = false;
        this.masteryLevel = 0;
        this.reviewStage = 0;
    }
    
    // 获取音标
    get phonetic() {
        return this.phonetic_symbol ? `/${this.phonetic_symbol}/` : '';
    }
    
    // 获取单词意思
    get meaning() {
        return this.mean || '';
    }
}

/**
 * 获取每日学习单词
 * @param {number} extraNewWords - 额外新词数量
 * @param {number} extraReviewWords - 额外复习词数量
 * @returns {Promise<Object>} 单词数据
 */
export async function getDailyStudyWords(extraNewWords = 0, extraReviewWords = 0) {
    try {
        const isAuthenticated = await api.isAuthenticated();
        if (!isAuthenticated) {
            return {
                newWords: [],
                reviewWords: [],
                dailyLimits: {
                    newWordsLimit: 10,
                    reviewWordsLimit: 20,
                    newWordsStudied: 0,
                    reviewWordsStudied: 0
                }
            };
        }
        
        const userId = await api.getUserId();
        
        // 构建请求参数
        let endpoint = `/api/words/daily/${userId}`;
        const params = [];
        
        if (extraNewWords > 0) {
            params.push(`newWordsLimit=${extraNewWords}`);
        }
        
        if (extraReviewWords > 0) {
            params.push(`reviewWordsLimit=${extraReviewWords}`);
        }
        
        if (params.length > 0) {
            endpoint += `?${params.join('&')}`;
        }
        
        // 发送请求获取数据
        const response = await api.get(endpoint);
        
        if (response && response.success && response.data) {
            // 转换单词数据为WordModel实例
            const newWords = (response.data.newWords || []).map(word => new WordModel(word));
            const reviewWords = (response.data.reviewWords || []).map(word => new WordModel(word));
            
            // 提取日常限制信息
            const dailyLimits = {
                newWordsLimit: response.data.dailyStats?.newWordsLimit || 10,
                reviewWordsLimit: response.data.dailyStats?.reviewWordsLimit || 20,
                newWordsStudied: response.data.dailyStats?.newWordsStudied || 0,
                reviewWordsStudied: response.data.dailyStats?.reviewWordsStudied || 0,
                newWordsRemaining: response.data.dailyStats?.newWordsRemaining || 10,
                reviewWordsRemaining: response.data.dailyStats?.reviewWordsRemaining || 20
            };
            
            // 保存到本地存储
            await saveDailyWords(newWords, reviewWords, dailyLimits);
            
            // 更新同步时间
            await updateLastSyncTime();
            
            return {
                newWords,
                reviewWords,
                dailyLimits
            };
        }
        
        // 如果网络请求失败，尝试从本地获取
        return await getLocalDailyWords();
    } catch (error) {
        console.error('获取每日单词失败:', error);
        
        // 发生错误时，尝试从本地获取
        return await getLocalDailyWords();
    }
}

/**
 * 从本地获取每日单词
 * @returns {Promise<Object>} 本地存储的单词数据
 */
async function getLocalDailyWords() {
    try {
        const dailyWordsStr = await storage.get({
            key: DAILY_WORDS_KEY,
            default: ''
        });
        
        if (dailyWordsStr && dailyWordsStr.trim() !== '') {
            const dailyWords = JSON.parse(dailyWordsStr);
            
            // 转换单词数据为WordModel实例
            const newWords = (dailyWords.newWords || []).map(word => new WordModel(word));
            const reviewWords = (dailyWords.reviewWords || []).map(word => new WordModel(word));
            
            return {
                newWords,
                reviewWords,
                dailyLimits: dailyWords.dailyLimits || {
                    newWordsLimit: 10,
                    reviewWordsLimit: 20,
                    newWordsStudied: 0,
                    reviewWordsStudied: 0
                }
            };
        }
        
        // 如果本地也没有，返回空数据
        return {
            newWords: [],
            reviewWords: [],
            dailyLimits: {
                newWordsLimit: 10,
                reviewWordsLimit: 20,
                newWordsStudied: 0,
                reviewWordsStudied: 0
            }
        };
    } catch (error) {
        console.error('获取本地每日单词失败:', error);
        
        // 出错时返回空数据
        return {
            newWords: [],
            reviewWords: [],
            dailyLimits: {
                newWordsLimit: 10,
                reviewWordsLimit: 20,
                newWordsStudied: 0,
                reviewWordsStudied: 0
            }
        };
    }
}

/**
 * 保存每日单词到本地
 * @param {Array} newWords - 新单词
 * @param {Array} reviewWords - 复习单词
 * @param {Object} dailyLimits - 每日限制
 */
async function saveDailyWords(newWords, reviewWords, dailyLimits) {
    try {
        const dailyWords = {
            newWords,
            reviewWords,
            dailyLimits,
            timestamp: Date.now()
        };
        
        await storage.set({
            key: DAILY_WORDS_KEY,
            value: JSON.stringify(dailyWords)
        });
    } catch (error) {
        console.error('保存每日单词失败:', error);
    }
}

/**
 * 记录单词学习情况
 * @param {number} wordId - 单词ID
 * @param {boolean} isCorrect - 是否正确
 * @param {boolean} isNewWord - 是否为新词
 * @returns {Promise<Object>} 学习结果
 */
export async function recordWordStudy(wordId, isCorrect, isNewWord) {
    try {
        const isAuthenticated = await api.isAuthenticated();
        
        if (!isAuthenticated) {
            return { success: false, message: '用户未登录' };
        }
        
        const userId = await api.getUserId();
        
        // 调用API记录学习情况
        const response = await api.post('/api/words/study', {
            userId,
            wordId,
            isCorrect,
            isNewWord
        });
        
        if (response && response.success) {
            // 记录学习历史到本地
            await saveStudyHistory(wordId, isCorrect, isNewWord);
            
            return {
                success: true,
                masteryLevel: response.mastery_level || 0,
                isReviewComplete: response.is_mastered || false,
                learningDetails: response.learning_details || null
            };
        }
        
        return { success: false, message: '记录学习失败' };
    } catch (error) {
        console.error('记录单词学习失败:', error);
        
        // 记录学习历史到本地（即使API失败）
        await saveStudyHistory(wordId, isCorrect, isNewWord);
        
        return { success: false, message: '记录学习请求失败' };
    }
}

/**
 * 保存学习历史到本地
 * @param {number} wordId - 单词ID
 * @param {boolean} isCorrect - 是否正确
 * @param {boolean} isNewWord - 是否为新词
 */
async function saveStudyHistory(wordId, isCorrect, isNewWord) {
    try {
        // 获取现有历史
        const historyStr = await storage.get({
            key: WORD_HISTORY_KEY,
            default: '[]'
        });
        
        const history = JSON.parse(historyStr);
        
        // 添加新记录
        history.push({
            wordId,
            isCorrect,
            isNewWord,
            timestamp: Date.now()
        });
        
        // 限制历史记录数量，保留最近300条
        const trimmedHistory = history.slice(-300);
        
        // 保存回存储
        await storage.set({
            key: WORD_HISTORY_KEY,
            value: JSON.stringify(trimmedHistory)
        });
    } catch (error) {
        console.error('保存学习历史失败:', error);
    }
}

/**
 * 获取单词详情
 * @param {number} wordId - 单词ID
 * @returns {Promise<WordModel|null>} 单词详情
 */
export async function getWordById(wordId) {
    try {
        const response = await api.get(`/api/words/${wordId}`);
        
        if (response && response.success && response.data && response.data.word) {
            return new WordModel(response.data.word);
        }
        
        return null;
    } catch (error) {
        console.error('获取单词详情失败:', error);
        return null;
    }
}

/**
 * 更新最后同步时间
 */
async function updateLastSyncTime() {
    try {
        await storage.set({
            key: LAST_SYNC_KEY,
            value: Date.now().toString()
        });
    } catch (error) {
        console.error('更新同步时间失败:', error);
    }
}

/**
 * 获取最后同步时间
 * @returns {Promise<number>} 最后同步时间戳
 */
export async function getLastSyncTime() {
    try {
        const timeStr = await storage.get({
            key: LAST_SYNC_KEY,
            default: '0'
        });
        
        return parseInt(timeStr);
    } catch (error) {
        console.error('获取同步时间失败:', error);
        return 0;
    }
}

/**
 * 获取学习统计
 * @returns {Promise<Object>} 学习统计
 */
export async function getStudyStats() {
    try {
        const isAuthenticated = await api.isAuthenticated();
        
        if (!isAuthenticated) {
            return {
                totalStudiedWords: 0,
                masteredWords: 0,
                todayNewWords: 0,
                todayReviewWords: 0
            };
        }
        
        const userId = await api.getUserId();
        
        const response = await api.get(`/api/words/stats/${userId}`);
        
        if (response && response.success && response.data) {
            return {
                totalStudiedWords: response.totalStudiedWords || 0,
                masteredWords: response.masteredWords || 0,
                todayNewWords: response.todayLearned?.newWords || 0,
                todayReviewWords: response.todayLearned?.reviewWords || 0,
                streakDays: response.streakDays || 0
            };
        }
        
        return {
            totalStudiedWords: 0,
            masteredWords: 0,
            todayNewWords: 0,
            todayReviewWords: 0,
            streakDays: 0
        };
    } catch (error) {
        console.error('获取学习统计失败:', error);
        
        return {
            totalStudiedWords: 0,
            masteredWords: 0,
            todayNewWords: 0,
            todayReviewWords: 0,
            streakDays: 0
        };
    }
} 